package club.framework.web.shiro.realm;

import club.framework.web.application.shiro.mapper.ShiroMapper;
import club.framework.web.application.sys.user.entity.User;
import club.framework.web.base.common.Constants;
import club.framework.web.base.common.Crypto;
import club.framework.web.shiro.token.BaseUsernamePasswordToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @date 2017/9/13.
 * @Email:sunmch@163.com
 * @author: 念梓
 * des:
 */

public class BaseAuthorizationRealm extends AuthorizingRealm {



    private static final Logger log = LogManager.getLogger(BaseAuthorizationRealm.class);

    private static final String UNIVERSAL_VALIDATE_CODE="1111";   //免死验证码，只要输入1111不在验证验证码的正确性

    @Resource
    private ShiroMapper shiroMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        BaseUsernamePasswordToken usernamePasswordToken = (BaseUsernamePasswordToken) token;
        String password = new String(usernamePasswordToken.getPassword());
        String username = usernamePasswordToken.getUsername();
        String validatecode = usernamePasswordToken.getValidatecode();
        Session session = getSession();
        String sessionValidateCode = (String) session.getAttribute(Constants.VALIDATE_CODE);
        if(!UNIVERSAL_VALIDATE_CODE.equals(validatecode)){   //免死验证码
            if (validatecode == null) {
                session.setAttribute("error", "验证码不能为空");
                throw new AuthenticationException("验证码不能为空");
            } else {
                if (!validatecode.equalsIgnoreCase(sessionValidateCode)) {
                    session.setAttribute("error", "您输入的验证码不正确");
                    throw new AuthenticationException("验证码不能为空");
                }
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("username",username);
        try {
            map.put("password", Crypto.getInstance().encrypt(password,Constants.DB_USERINFO_ENCRYPT_KEY));
        } catch (Exception e) {
            log.error("登录的密码: {},加密失败: {}",password,e.getMessage());
            throw new AuthenticationException("用户名或密码不正确");
        }
        User user = shiroMapper.queryUser(map);
        if (null == user) {
            session.setAttribute("error", "用户名或密码不正确");
            throw new AuthenticationException("用户名或密码不正确");
        }
        session.setAttribute(Constants.USER_INFO,user);
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password, username);
        return authenticationInfo;
    }

    private Session getSession() {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        return session;
    }

}
